/*
 * @Author: i@rysa.cn
 * @Date: 2022-05-14 16:53:24
 * @LastEditTime: 2022-05-14 16:53:27
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\wechat\mp\sns\sns.go
 */
package sns

import (
	"encoding/json"
	"fmt"

	"gitee.com/rysa/go-utils/request"
	"gitee.com/rysa/go-utils/wechat/mp/mpconfig"
	"gitee.com/rysa/go-utils/wechat/mp/params"
)

const (
	snsUrl = "https://api.weixin.qq.com/sns/oauth2/"
)

type sns struct {
	*mpconfig.MpConfig
}

func NewSns(cfg *mpconfig.MpConfig) *sns {
	return &sns{cfg}
}

/**
 * @name: 获取基础权限信息
 * @description: 不需要用户授权
 * @param {string} code
 * @return {*}
 */
func (mp *sns) GetBaseInfo(code string) params.SnsBaseInfo {
	req := request.NewRequest()
	url := snsUrl + fmt.Sprintf("access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", mp.Appid, mp.Appsecret, code)
	var info params.SnsBaseInfo
	res, err := req.Get(url)
	if err != nil {
		return params.SnsBaseInfo{
			Errcode: -1,
			Errmsg:  err.Error(),
		}
	}
	json.Unmarshal(res.Body(), &info)
	return info
}

/**
 * @name: 获取用户信息，需要用户授权
 * @description: scope为 snsapi_userinfo
 * @param {string} code
 * @return {*}
 */
func (mp *sns) GetSnsUserInfo(code string) params.SnsUserInfo {
	info := mp.GetBaseInfo(code)
	if info.Errcode != 0 {
		return params.SnsUserInfo{
			Errcode: info.Errcode,
			Errmsg:  info.Errmsg,
		}
	}
	// 获取用户信息
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", info.AccessToken, info.Openid)
	req := request.NewRequest()
	res, err := req.Get(url)
	if err != nil {
		return params.SnsUserInfo{
			Errcode: -1,
			Errmsg:  err.Error(),
		}
	}
	var result params.SnsUserInfo
	json.Unmarshal(res.Body(), &result)
	return result
}
